#include <zlib/lib/Ink_pthread.h>
#include <iostream>
#include <unistd.h>

using namespace std;
ink_cond g_cond;
ink_mutex g_mutex;
int i = 0;

struct param{
	int a;
	int b;
};

void *start_fun1(void *arg)
{
	struct param *p = (struct param *)arg;
	cout << "fun1:" << p->a << " " << p->b << endl;
	sleep(3);
	return NULL;
}

void *start_fun2(void *arg)
{
	cout << "test condition" << endl;
	
	ink_mutex_lock(&g_mutex);
	while(i == 0)
		ink_cond_wait(&g_cond, &g_mutex);
	cout << "i:" << i << endl;
	ink_mutex_release(&g_mutex);

	cout << "test condition time wait" << endl;
	ink_mutex_lock(&g_mutex);
	struct timespec time;
	time.tv_sec = 2;
	time.tv_nsec = 0;
	ink_cond_time_wait(&g_cond, &g_mutex, &time);
	cout << "time wait..." << endl;
	ink_mutex_release(&g_mutex);
}


int main()
{
	ink_thread tid;
	ink_mutex mutex;
	ink_thread_key key;

	struct param *p = (struct param *)malloc(sizeof(struct param));
	p->a = 10;
	p->b = 20;
	//not deatch thread
	tid = ink_thread_create(start_fun1, (void *)p);
	ink_thread_join(tid, NULL);
	cout << "after 5s....." << endl;

	cout << "testing mutex" << endl;
	ink_mutex_init(&mutex);
	ink_mutex_lock(&mutex);
	int status = ink_mutex_try_lock(&mutex);
	if(status) {
		cout << "lock success" << endl;
	}else{
		cout << "lock faild" << endl;
	}
	ink_mutex_release(&mutex);

	status = ink_mutex_try_lock(&mutex);
	if(status) {
		cout << "lock success" << endl;
	}else{
		cout << "lock faild" << endl;
	}
	ink_mutex_release(&mutex);
	ink_mutex_destroy(&mutex);
	cout << "destory mutex" << endl;

	cout << "test deatch thread" << endl;
	ink_cond_init(&g_cond);
	ink_mutex_init(&g_mutex);
	ink_thread_create(start_fun2, NULL, 1);
	sleep(5);
	i = 2;
	sleep(3);
	ink_mutex_lock(&g_mutex);
	ink_cond_signal(&g_cond);
	ink_mutex_release(&g_mutex);

	sleep(5);
}
